<template>
  <div class="bind-email-form">
    <n-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      size="medium"
      :show-label="false"
    >
      <n-form-item path="email">
        <n-input
          v-model:value="formData.email"
          placeholder="请输入邮箱地址"
          :disabled="loading"
        >
          <template #prefix>
            <n-icon :size="18">
              <MailOutline />
            </n-icon>
          </template>
        </n-input>
      </n-form-item>

      <n-form-item path="captcha">
        <div class="captcha-container">
          <n-input
            v-model:value="formData.captcha"
            placeholder="请输入验证码"
            :disabled="loading"
          >
            <template #prefix>
              <n-icon :size="18">
                <ShieldCheckmarkOutline />
              </n-icon>
            </template>
          </n-input>
          <n-button
            :disabled="loading || countdown > 0 || !formData.email"
            :loading="sendingCode"
            @click="sendVerificationCode"
            class="send-code-btn"
          >
            {{ countdown > 0 ? `${countdown}s` : '发送验证码' }}
          </n-button>
        </div>
      </n-form-item>

      <div class="form-actions">
        <n-button @click="$emit('cancel')" :disabled="loading">
          取消
        </n-button>
        <n-button
          type="primary"
          :loading="loading"
          @click="handleSubmit"
        >
          确认绑定
        </n-button>
      </div>
    </n-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { useMessage } from 'naive-ui'
import { useUserStore } from '@/stores/user'
import { changeBind, verifyAccount } from '@/api/account'
import { sendEmailCode } from '@/api/user'
import { commonRules } from '@/utils/validation'
import type { FormInst } from 'naive-ui'
import type { ChangeBindParams } from '@/types/user'
import {
  MailOutline,
  ShieldCheckmarkOutline
} from '@vicons/ionicons5'

interface Emits {
  (e: 'success'): void
  (e: 'cancel'): void
}

const emit = defineEmits<Emits>()
const message = useMessage()
const userStore = useUserStore()

// 表单引用
const formRef = ref<FormInst | null>(null)

// 表单数据
const formData = reactive<ChangeBindParams>({
  email: '',
  captcha: ''
})

// 状态
const loading = ref(false)
const sendingCode = ref(false)
const countdown = ref(0)

// 表单验证规则
const formRules = {
  email: commonRules.email,
  captcha: commonRules.captcha
}

// 发送验证码
const sendVerificationCode = async () => {
  if (!formRef.value) return
  
  // 验证邮箱字段
  try {
    await formRef.value.validate(undefined, (rule) => rule.key === 'email')
  } catch {
    return
  }
  
  try {
    sendingCode.value = true
    await sendEmailCode(formData.email!, 'user_change_email')
    
    message.success('验证码已发送')
    startCountdown()
  } catch (error: any) {
    console.error('发送验证码失败:', error)
    message.error(error.message || '发送验证码失败')
  } finally {
    sendingCode.value = false
  }
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    // 如果用户已绑定邮箱，需要先验证当前邮箱
    if (userStore.email) {
      // 这里应该先验证当前邮箱，简化处理
      message.info('请先验证当前邮箱')
      return
    }
    
    await changeBind(formData)
    message.success('邮箱绑定成功')
    emit('success')
  } catch (error: any) {
    console.error('绑定邮箱失败:', error)
    message.error(error.message || '绑定邮箱失败，请重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.bind-email-form {
  padding: 8px 0;
}

.captcha-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.captcha-container .n-input {
  flex: 1;
}

.send-code-btn {
  white-space: nowrap;
  min-width: 100px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 16px;
}
</style>
